package com.kawa.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.math.MathUtil;
import cn.hutool.core.util.RandomUtil;
import com.kawa.constant.CaptchaConstants;
import com.kawa.constant.CommonConstants;
import com.kawa.model.R;
import com.kawa.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.awt.*;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: KAIyo
 * @Date: 2025/7/21 10:01
 * @Version: v1.0.0
 * @Description: TODO
 **/
@RestController
@ResponseBody
@RequestMapping("/captcha")
public class CaptchaController {
    @Autowired
    private RedisUtil redisUtil;

    @GetMapping("/image")
    public R getCaptcha(){
        //TODO 生成验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(134, 40);
        //验证码id
        String captchaId = String.valueOf(lineCaptcha.hashCode());
        //生成的验证码
        String captchaCode = lineCaptcha.getCode();
        Map<String, Object> resultMap = null;
        //验证码的key,确保不会重复
        String redisKey = CaptchaConstants.CAPTCHA_CODE_KEY + captchaId + CommonConstants.DASH + captchaCode;

        //存入redis并设置过期时间
        //先看是否存在
        if (redisUtil.hasKey(redisKey)){
            //TODO
        }else {
            //存储到redis中进行验证,随机过期时间防止雪崩
            redisUtil.setEx(redisKey, captchaCode, RandomUtil.randomInt(180, 200), TimeUnit.SECONDS);
            //完成生成并返回
            resultMap = new HashMap<>();
            resultMap.put("image", lineCaptcha.getImageBase64Data());
            resultMap.put("captchaId", redisKey);
        }

        return R.ok(resultMap);
    }
}
